﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TGVR_Boot.DTO;
using HtmlAgilityPack;
using System.Net;
using System.IO;
using PortalTicket.DAO;
using System.Threading;
using System.Globalization;
using MDF.Cacher.Managements;
using MDF.Worker;
using TGVR_Boot.Workers;
using MDF.Logger.Managements;
using MDF.Utilites.Helper;
using DataHelper;
using PortalBooking.BUS;
using MDF.Requesting;

namespace TGVR_Boot
{
    public class MuaDiBoot : IBoot
    {
        //static string m_strHomeLink = "http://www.bookingticket.vn/";
        static string m_strHomeLink = "http://www.systemvna.com/";
        Requester m_request = new Requester();

        public static Thread m_tryLogin = null;

        System.Net.CookieContainer co = new System.Net.CookieContainer();

        public MuaDiBoot()
        {
            string cokie = "ASP.NET_SessionId=" + new SettingDAO().GetSetting("SessionVN") + "; CookieBookerInterface=BOOKER; TbsClientSite.CurrentUICulture=en-US";
            string login = m_strHomeLink;
            co.SetCookies(new Uri(login), cokie);
            if (m_tryLogin == null)
            {
                m_tryLogin = new Thread(new ThreadStart(TryLogin));
                m_tryLogin.IsBackground = true;
                m_tryLogin.Start();
            }
        }

        public static void TryLogin()
        {
            while (true)
            {
                try
                {
                    string cokie = "ASP.NET_SessionId=" + new SettingDAO().GetSetting("SessionVN") + "; CookieBookerInterface=BOOKER; TbsClientSite.CurrentUICulture=en-US";
                    string login = m_strHomeLink;

                    System.Net.CookieContainer cos = new System.Net.CookieContainer();
                    cos.SetCookies(new Uri(login), cokie);

                    Requester rq = new Requester();

                    var res = rq.GetData(login, false, cos);

                    string strBookingVNLink = m_strHomeLink+"SabreComand/SabreCommand";
                    Requester rqBookingVN = new Requester();
                    rqBookingVN.Cookie = cokie;

                    var resBookingVN = rqBookingVN.GetData(strBookingVNLink);
                    string strHtmlMBookingVN = rqBookingVN.GetHtmlFromResponse(resBookingVN);

                    string html = rq.GetHtmlFromResponse(res);

                    if (html.IndexOf("Logout") == -1 || strHtmlMBookingVN.IndexOf("Logout") == -1)
                    {
                        SettingDAO st = new SettingDAO();
                        st.SetSetting("NeedRefreshSessionVN", "True");
                        LogManager.GetInstance().Warning("Need Refresh Session VNr");
                    }
                    else
                    {
                        try
                        {
                            SettingDAO st = new SettingDAO();
                            st.SetSetting("NeedRefreshSessionVN", "False");
                            int iTemp = Int32.Parse(st.GetSetting("testtrylogin"));
                            iTemp++;
                            st.SetSetting("testtrylogin", iTemp.ToString());
                        }
                        catch(Exception ex)
                        {
                            LogManager.GetInstance().Error("Update setting VN Error", ex);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogManager.GetInstance().Error("Try Login VN Error",ex);
                }

                Thread.Sleep(1000 * 60 * 5);
            }
        }

        public string GetError()
        {
            return m_error;
        }

        /// <summary>
        /// Lấy mã vé
        /// </summary>
        /// <returns></returns>
        public string GetCode()
        {
            return resnumber;
        }
        /// <summary>
        /// Lấy tổng tiền
        /// </summary>
        /// <returns></returns>
        public int GetTotal()
        {
            try
            {
                int iTotal = 0, iFee = 0 ;
                thanhtien = thanhtien.Trim();
                if (!string.IsNullOrEmpty(thanhtien))
                    iTotal=  Int32.Parse(thanhtien.Replace(".", ""));
                phixuatve = phixuatve.Trim();
                if (!string.IsNullOrEmpty(phixuatve))
                    iFee =  Int32.Parse(phixuatve.Replace(".", ""));
                return iTotal - iFee;
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("VNs: Cant get total price!", ex);
            }

            return 0;
        }

        public List<TicketDTO> Search(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
          int _iAdut, int _iChild, int _iBaby, bool _isInter)
        {
            string strKeyword = "VietNamAirline" + _strStationForm + _strStationTo + _dtDateFrom.ToString("MMddyyyyhhmm") +
                (_dtDateTo.HasValue ? _dtDateTo.Value.ToString("MMddyyyyhhmm") : "") + _iAdut.ToString() + _iChild.ToString() + _iBaby.ToString() + "_User" + SettingDAO.UserID;
            //m_log.Info("Search: " + strKeyword);
            var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            if (cacheResult != null)
            {
                //m_log.Info("Get from cache");
                return (List<TicketDTO>)cacheResult;
            }

            List<TicketDTO> lstResult = new List<TicketDTO>();

            if (_dtDateTo != null)
                lstResult = SearchTwoWay(_strStationForm, _strStationTo, _dtDateFrom, _dtDateTo,
           _iAdut, _iChild, _iBaby, _isInter);
            else
                lstResult = SearchOneWay(_strStationForm, _strStationTo, _dtDateFrom, _dtDateTo,
           _iAdut, _iChild, _iBaby, _isInter);

            if (lstResult != null && lstResult.Count > 0)
            {
                CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
            }
            else
                lstResult = new List<TicketDTO>();

            return lstResult;

            //tìm trong phần đăng nhập


            //Requester rq = new Requester();


            //string strReturnDay = _dtDateTo.HasValue ? _dtDateTo.Value.Day.ToString() : "";
            //string strReturnMonth = _dtDateTo.HasValue ? "returnDate=" + _dtDateTo.Value.ToString("yyyy-MM-d") : "";
            //string strRound = _dtDateTo.HasValue ? "RT" : "OW";

            //string strTemp = string.Format("https://wl-prod.sabresonicweb.com/SSW2010/B3QE/webqtrip.html?searchType=NORMAL&lang=vt&journeySpan={7}&origin={0}&destination={1}&numAdults={2}&numChildren={3}&numInfants={4}&promoCode=&radio_choice=on&txtRecordLocator=&txtETicketNumber=&txtFFNumber=&alternativeLandingPage=true&departureDate={5}&{6}",
            //    _strStationForm,
            //    _strStationTo,
            //    _iAdut,
            //    _iChild,
            //    _iBaby,
            //    _dtDateFrom.ToString("yyyy-MM-d"),
            //    strReturnMonth,
            //    strRound
            //    );

            //var respone = rq.GetData(strTemp);

            //if (respone != null)
            //{
            //    string htmlRespone = rq.GetHtmlFromResponse(respone);
            //    var lstResult = new List<TicketDTO>();
            //    HtmlDocument doc = new HtmlDocument();
            //    doc.LoadHtml(htmlRespone);
            //    //kiểm tra tìm vé không thành công
            //    string strTag = "//*[@id=\"dtcontainer-outbounds\"]//tr";//
            //    if (!_dtDateTo.HasValue)
            //        strTag = "//*[@id=\"dtcontainer-both\"]//tr";
            //    var travlesOut = doc.DocumentNode.SelectNodes(strTag);
            //    if (travlesOut.Count > 1)//bo title[0]
            //    {
            //        //từng vé
            //        for (int i = 1; i < travlesOut.Count; i++)
            //        {
            //            var ticket = travlesOut[i];
            //            HtmlDocument docTicket = new HtmlDocument();
            //            docTicket.LoadHtml(ticket.InnerHtml);
            //            if (docTicket == null)
            //                continue;
            //            var tempVar = docTicket.DocumentNode.SelectNodes("//td");


            //            TicketDTO t = new TicketDTO();

            //            t.FlightNo = tempVar[0].InnerText.Trim();
            //            t.DateEnd = DateTime.Parse(_dtDateFrom.ToString("MM/dd/yyyy") + " " + tempVar[3].InnerText.Trim());
            //            t.DateStart = DateTime.Parse(_dtDateFrom.ToString("MM/dd/yyyy") + " " + tempVar[2].InnerText.Trim());

            //            t.From = _strStationForm;
            //            t.LastUpdate = DateTime.Now;
            //            t.ReturnDate = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("dd/MM/yyyy") : "";
            //            t.To = _strStationTo;

            //            var tempPrice = docTicket.DocumentNode.SelectNodes("//*[@class=\"prices-amount\"]");

            //            string strPrice = tempPrice[tempPrice.Count - 1].InnerText.Trim();

            //            t.PriceBefore = Int32.Parse(strPrice.Replace(",", ""));
            //            t.Price = t.PriceBefore + 50000;
            //            //t.Price += 60000;


            //            t.TypeWay = "Out";
            //            t.Image = "http://thegioivere.net/content/images/logo/VN.png";
            //            lstResult.Add(t);
            //        }
            //        if (_dtDateTo.HasValue)
            //        {
            //            var travlesIn = doc.DocumentNode.SelectNodes("//*[@id=\"dtcontainer-inbounds\"]//tr");
            //            if (travlesIn.Count > 1)//bo title[0]
            //            {
            //                //từng vé
            //                for (int i = 1; i < travlesIn.Count; i++)
            //                {
            //                    var ticket = travlesIn[i];
            //                    HtmlDocument docTicket = new HtmlDocument();
            //                    docTicket.LoadHtml(ticket.InnerHtml);
            //                    if (docTicket == null)
            //                        continue;

            //                    var tempVar = docTicket.DocumentNode.SelectNodes("//td");


            //                    TicketDTO t = new TicketDTO();
            //                    t.AirType = "vietnam";
            //                    t.FlightNo = tempVar[0].InnerText.Trim();
            //                    t.DateEnd = DateTime.Parse(_dtDateTo.Value.ToString("MM/dd/yyyy") + " " + tempVar[3].InnerText.Trim());
            //                    t.DateStart = DateTime.Parse(_dtDateTo.Value.ToString("MM/dd/yyyy") + " " + tempVar[2].InnerText.Trim());

            //                    t.From = _strStationForm;
            //                    t.LastUpdate = DateTime.Now;
            //                    t.ReturnDate = _dtDateTo.HasValue ? _dtDateTo.Value.ToString("dd/MM/yyyy") : "";
            //                    t.To = _strStationTo;

            //                    var tempPrice = docTicket.DocumentNode.SelectNodes("//*[@class=\"prices-amount\"]");

            //                    string strPrice = tempPrice[tempPrice.Count - 1].InnerText.Trim();


            //                    t.PriceBefore = Int32.Parse(strPrice.Replace(",", ""));
            //                    t.Price = t.PriceBefore + 50000;

            //                    t.TypeWay = "In";
            //                    t.Image = "http://thegioivere.net/content/images/logo/VN.png";
            //                    lstResult.Add(t);
            //                }
            //            }
            //        }
            //    }
            //    if (lstResult != null)
            //    {
            //        CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
            //    }
            //    //m_log.Info("Return " + lstResult.Count +" results");
            //    return lstResult;
            //}
            //return null;
        }

        public List<TicketDTO> SearchOneWay(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
          int _iAdut, int _iChild, int _iBaby, bool _isInter)
        {
            List<TicketDTO> lstResult = new List<TicketDTO>();
            string html = "";
            string strRound = "ONEWAY";
            if (!Login())
            {
                LogManager.GetInstance().Warning("Not login VietnamAir");
                return null;
            }
            var data = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("Action", "SEARCHFLIGHT"),
                new KeyValuePair<string, string>("OldSearchType", ""),
                new KeyValuePair<string, string>("SearchType", strRound),
                new KeyValuePair<string, string>("SearchRoundTripDepartureCity",_strStationForm),
                new KeyValuePair<string, string>("SearchRoundTripArrivalCity", _strStationTo),
                new KeyValuePair<string, string>("SearchRoundTripDepartureDate" ,_dtDateFrom.ToString("dd/MM/yyyy")),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", _strStationForm),
                new KeyValuePair<string, string>("SearchOneWayArrivalCity", _strStationTo),
                new KeyValuePair<string, string>("SearchOneWayDepartureDate", _dtDateFrom.ToString("dd/MM/yyyy")),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", "SGN"),
            });
            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");

            var request = (HttpWebRequest)WebRequest.Create(m_strHomeLink+"Booking/BookManage");
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.CookieContainer = co;
            using (var requestStream = request.GetRequestStream())
            using (var writer = new StreamWriter(requestStream))
            {
                foreach (var item in data)
                {
                    writer.WriteLine("--" + boundary);
                    writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", item.Key));
                    writer.WriteLine();
                    writer.WriteLine(item.Value);
                }
                writer.WriteLine(boundary + "--");
            }

            string strOutTicket = "";
            using (var response = request.GetResponse())
            using (var responseStream = response.GetResponseStream())
            using (var reader = new StreamReader(responseStream))
            {
                html = reader.ReadToEnd();
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                //*[@class=\"TblGrid\"]//tr

                var ticketNodes = doc.DocumentNode.SelectNodes("//*[@class=\"TblGrid\"]//tr");

                string strFee = "FeeVietnamAirline";
                if (_isInter)
                    strFee = "FeeVietnamAirlineInter";
                decimal iFee = Int32.Parse(new SettingDAO().GetSetting(strFee));
                var iDollar = Int32.Parse(new SettingDAO().GetSetting("Dollar"));

                //int OutputFee_VN = Int32.Parse(new SettingDAO().GetSetting("OutputFee_VN"));
                FirmDAO fDAO = new FirmDAO();
                var vnFirm = fDAO.GetByShortName("VN");

                bool isNeedModifyTax = false;
                decimal iTaxModified = 0;

                if (_strStationForm + _strStationTo == "SGNBKK" ||
                    _strStationForm + _strStationTo == "BKKSGN"
                    )
                {
                    isNeedModifyTax = true;
                    iTaxModified = decimal.Parse(new SettingDAO().GetSetting("TaxVN_SGNBKK" + (_dtDateTo.HasValue ? "" : "1")));
                }

                if (_strStationForm + _strStationTo == "HANBKK" ||
                    _strStationForm + _strStationTo == "BKKHAN"
                    )
                {
                    isNeedModifyTax = true;
                    iTaxModified = decimal.Parse(new SettingDAO().GetSetting("TaxVN_HANBKK" + (_dtDateTo.HasValue ? "" : "1")));
                }

                if (_strStationForm + _strStationTo == "SGNSIN" ||
                    _strStationForm + _strStationTo == "SINSGN"
                    )
                {
                    isNeedModifyTax = true;
                    iTaxModified = decimal.Parse(new SettingDAO().GetSetting("TaxVN_SGNSIN" + (_dtDateTo.HasValue ? "" : "1")));
                }

                if (_strStationForm + _strStationTo == "HANSIN" ||
                    _strStationForm + _strStationTo == "SINHAN"
                    )
                {
                    isNeedModifyTax = true;
                    iTaxModified = decimal.Parse(new SettingDAO().GetSetting("TaxVN_HANSIN" + (_dtDateTo.HasValue ? "" : "1")));
                }

                foreach (var item in ticketNodes)
                {
                    HtmlDocument docTicket = new HtmlDocument();
                    docTicket.LoadHtml(item.InnerHtml);

                    var OutTickets = docTicket.DocumentNode.SelectNodes(string.Format("//a[contains(@onclick,'FillToBooking') and contains(@onclick,'AGT') and contains(@onclick,'{0};{1};') and contains(@onclick,'{2}')]",//SGN;HAN;VN234;06/01/2014;0930
                    _strStationForm.ToUpper(),//0
                    _strStationTo.ToUpper(),//1
                    _dtDateFrom.ToString("dd/MM/yyyy")//2
                        )
                    );//

                    if (OutTickets != null && OutTickets.Count > 0)
                    {
                        for (int i = OutTickets.Count - 1; i >= 0; i--)
                        {
                            string strclass = OutTickets[i].InnerText.Trim();
                            if (strclass[0] == 'X')
                                continue;
                            strclass = strclass.Substring(1);
                            if (!string.IsNullOrEmpty(strclass)
                                && strclass != "0"
                                && Int32.Parse(strclass) >= _iAdut + _iBaby + _iChild
                                )
                            {
                                strOutTicket = OutTickets[i].Attributes["onclick"].Value;
                                strOutTicket = strOutTicket.Substring(strOutTicket.IndexOf('\'') + 1, strOutTicket.LastIndexOf('\'') - strOutTicket.IndexOf('\'') - 1);
                                // SGN;HAN;VN244;10/01/2014;1300;J;4,600,000;NN;3;VN130471F_J;AGT;5,120,000
                                //'SGN;HAN;VN234;06/01/2014;0930;M;2,670,000;LL;1;VN130471F_M;AGT;2,997,000
                                //  0   1     2      3        4  5     6     7  8      9      10     11
                                var arrOut = strOutTicket.Split(';');
                                TicketDTO t = new TicketDTO();
                                t.IsInter = _isInter;
                                t.AirType = "vietnam";
                                t.From = arrOut[0];
                                t.To = arrOut[1];
                                t.FlightNo = arrOut[2];
                                t.DateStart = DateTime.ParseExact(arrOut[3] + ";" + arrOut[4], "dd/MM/yyyy;HHmm", CultureInfo.InvariantCulture);
                                t.DateEnd = t.DateStart;
                                t.DataToBook = strOutTicket;
                                //t.OutputFee = OutputFee_VN;
                                t.ChildPricePercent = vnFirm.Child;
                                t.BabyPricePercent = vnFirm.Baby;
                                int iPriceTemp = Int32.Parse(arrOut[6].Replace(",", ""));

                                t.PriceBefore = iPriceTemp;
                                if (_isInter)
                                {
                                    t.PriceBefore = iPriceTemp * iDollar;//giá net
                                    if (isNeedModifyTax)
                                    {
                                        t.Price = (int)((iPriceTemp + iTaxModified) * iDollar + iFee);
                                    }
                                    else
                                    {
                                        t.Price = Int32.Parse(arrOut[11].Replace(",", "")) * iDollar + (int)iFee;
                                    }
                                }
                                else
                                {
                                    t.Price = Int32.Parse(arrOut[11].Replace(",", "")) + (int)iFee;
                                }
                                t.TypeWay = "Out";
                                t.Image = "http://thegioivere.net/content/images/logo/VN.png";

                                string dateEnd = docTicket.DocumentNode.SelectNodes("//td[6]")[0].InnerText.Split('-')[1];
                                t.DateEnd = DateTime.ParseExact(arrOut[3] + ";" + dateEnd, "dd/MM/yyyy;HHmm", CultureInfo.InvariantCulture);

                                lstResult.Add(t);
                                break;
                            }
                        }
                    }
                }
            }

            return lstResult;
        }

        public List<TicketDTO> SearchTwoWay(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
          int _iAdut, int _iChild, int _iBaby, bool _isInter)
        {
            var lstResult = new List<TicketDTO>();
            string html = "";
            string strRound = "ROUNDTRIP";

            if (!Login())
            {
                LogManager.GetInstance().Warning("Not login VietnamAir");
                return null;
            }


            var data = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("Action", "SEARCHFLIGHT"),
                new KeyValuePair<string, string>("OldSearchType", ""),
                new KeyValuePair<string, string>("SearchType", strRound),
                new KeyValuePair<string, string>("SearchRoundTripDepartureCity", _strStationForm),
                new KeyValuePair<string, string>("SearchRoundTripArrivalCity", _strStationTo),
                new KeyValuePair<string, string>("SearchRoundTripDepartureDate" ,_dtDateFrom.ToString("dd/MM/yyyy")),
                new KeyValuePair<string, string>("SearchRoundTripArrivalDate",_dtDateTo!=null? _dtDateTo.Value.ToString("dd/MM/yyyy"):""),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", _strStationForm),
                new KeyValuePair<string, string>("SearchOneWayArrivalCity", _strStationTo),
                new KeyValuePair<string, string>("SearchOneWayDepartureDate", _dtDateFrom.ToString("dd/MM/yyyy")),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", "SGN"),
            });
            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");

            var request = (HttpWebRequest)WebRequest.Create(m_strHomeLink + "Booking/BookManage");
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.CookieContainer = co;
            using (var requestStream = request.GetRequestStream())
            using (var writer = new StreamWriter(requestStream))
            {
                foreach (var item in data)
                {
                    writer.WriteLine("--" + boundary);
                    writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", item.Key));
                    writer.WriteLine();
                    writer.WriteLine(item.Value);
                }
                writer.WriteLine(boundary + "--");
            }

            string strOutTicket = "";
            using (var response = request.GetResponse())
            using (var responseStream = response.GetResponseStream())
            using (var reader = new StreamReader(responseStream))
            {
                html = reader.ReadToEnd();
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                //*[@class=\"TblGrid\"]//tr

                var types = doc.DocumentNode.SelectNodes("//*[@class=\"TblGrid\"]");
                if (types == null)
                    return lstResult;

                string strFee = "FeeVietnamAirline";
                if (_isInter)
                    strFee = "FeeVietnamAirlineInter";
                decimal iFee = Int32.Parse(new SettingDAO().GetSetting(strFee));
        

                int OutputFee_VN = Int32.Parse(new SettingDAO().GetSetting("OutputFee_VN"));
                FirmDAO fDAO = new FirmDAO();
                var vnFirm = fDAO.GetByShortName("VN");
                //else
                //{
                //    if (_dtDateTo.HasValue)
                //        iFee *= 2;
                //    iFee /= (_iAdut + _iBaby + _iChild);
                //}
                var iDollar = Int32.Parse(new SettingDAO().GetSetting("Dollar"));

                bool isNeedModifyTax = false;
                decimal iTaxModified = 0;
                if (_strStationForm + _strStationTo == "SGNBKK" ||
                    _strStationForm + _strStationTo == "BKKSGN"
                    )
                {
                    isNeedModifyTax = true;
                    iTaxModified = decimal.Parse(new SettingDAO().GetSetting("TaxVN_SGNBKK" + (_dtDateTo.HasValue ? "" : "1")));
                }

                if (_strStationForm + _strStationTo == "HANBKK" ||
                    _strStationForm + _strStationTo == "BKKHAN"
                    )
                {
                    isNeedModifyTax = true;
                    iTaxModified = decimal.Parse(new SettingDAO().GetSetting("TaxVN_HANBKK" + (_dtDateTo.HasValue ? "" : "1")));
                }

                if (_strStationForm + _strStationTo == "SGNSIN" ||
                    _strStationForm + _strStationTo == "SINSGN"
                    )
                {
                    isNeedModifyTax = true;
                    iTaxModified = decimal.Parse(new SettingDAO().GetSetting("TaxVN_SGNSIN" + (_dtDateTo.HasValue ? "" : "1")));
                }

                if (_strStationForm + _strStationTo == "HANSIN" ||
                    _strStationForm + _strStationTo == "SINHAN"
                    )
                {
                    isNeedModifyTax = true;
                    iTaxModified = decimal.Parse(new SettingDAO().GetSetting("TaxVN_HANSIN" + (_dtDateTo.HasValue ? "" : "1")));
                }

                for (int iType = 0; iType < types.Count; iType++)
                {
                    HtmlDocument docTemp = new HtmlDocument();
                    docTemp.LoadHtml(types[iType].InnerHtml);

                    var ticketNodes = docTemp.DocumentNode.SelectNodes("//tr");

                    foreach (var item in ticketNodes)
                    {
                        HtmlDocument docTicket = new HtmlDocument();
                        docTicket.LoadHtml(item.InnerHtml);

                        var OutTickets = docTicket.DocumentNode.SelectNodes(string.Format("//a[contains(@onclick,'FillToBooking') and contains(@onclick,'AGT')]"));//
                        if (OutTickets != null && OutTickets.Count > 0)
                        {

                            for (int i = OutTickets.Count - 1; i >= 0; i--)
                            {
                                string strclass = OutTickets[i].InnerText.Trim();
                                if (strclass[0] == 'X')
                                    continue;
                                strclass = strclass.Substring(1);
                                if (!string.IsNullOrEmpty(strclass)
                                    && strclass != "0"
                                    && Int32.Parse(strclass) >= _iAdut + _iBaby + _iChild
                                    )
                                {
                                    strOutTicket = OutTickets[i].Attributes["onclick"].Value;
                                    strOutTicket = strOutTicket.Substring(strOutTicket.IndexOf('\'') + 1, strOutTicket.LastIndexOf('\'') - strOutTicket.IndexOf('\'') - 1);
                                    // SGN;HAN;VN244;10/01/2014;1300;J;4,600,000;NN;3;VN130471F_J;AGT;5,120,000
                                    //'SGN;HAN;VN234;06/01/2014;0930;M;2,670,000;LL;1;VN130471F_M;AGT;2,997,000
                                    //  0   1     2      3        4  5     6     7  8      9      10     11
                                    var arrOut = strOutTicket.Split(';');
                                    TicketDTO t = new TicketDTO();
                                    t.IsInter = _isInter;
                                    t.AirType = "vietnam";
                                    t.From = arrOut[0];
                                    t.To = arrOut[1];
                                    t.FlightNo = arrOut[2];
                                    t.DateStart = DateTime.ParseExact(arrOut[3] + ";" + arrOut[4], "dd/MM/yyyy;HHmm", CultureInfo.InvariantCulture);
                                    t.DateEnd = t.DateStart;
                                    t.DataToBook = strOutTicket;
                                    t.OutputFee = OutputFee_VN;
                                    t.ChildPricePercent = vnFirm.Child;
                                    t.BabyPricePercent = vnFirm.Baby;
                                    int iPriceTemp = Int32.Parse(arrOut[6].Replace(",", ""));

                                    t.PriceBefore = iPriceTemp;
                                    if (_isInter)
                                    {
                                        t.PriceBefore = iPriceTemp * iDollar;//giá net
                                        if (isNeedModifyTax)
                                        {
                                            t.Price = (int)((iPriceTemp + iTaxModified / 2) * iDollar + iFee);
                                        }
                                        else
                                        {
                                            t.Price = Int32.Parse(arrOut[11].Replace(",", "")) * iDollar + (int)iFee;
                                        }
                                    }
                                    else
                                    {
                                        t.Price = Int32.Parse(arrOut[11].Replace(",", "")) + (int)iFee;
                                    }
                                    if (iType == 0)
                                        t.TypeWay = "Out";
                                    if (iType == 1)
                                        t.TypeWay = "In";
                                    t.Image = "http://thegioivere.net/content/images/logo/VN.png";

                                    string dateEnd = docTicket.DocumentNode.SelectNodes("//td[6]")[0].InnerText.Split('-')[1];
                                    t.DateEnd = DateTime.ParseExact(arrOut[3] + ";" + dateEnd, "dd/MM/yyyy;HHmm", CultureInfo.InvariantCulture);

                                    lstResult.Add(t);
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            return lstResult;
        }

        private List<TicketDTO> m_lstResult = new List<TicketDTO>();

        private void ComineTickets(object data)
        {
            try
            {
                this.m_lstResult.AddRange((List<TicketDTO>)data);
            }
            catch (Exception ex)
            {
                LogManager.GetInstance().Error("VietNameAir: Lỗi tìm vé rẻ trong tháng", ex);
            }
        }

        public List<TicketDTO> SearchCheapest(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
            int _iAdut, int _iChild, int _iBaby)
        {

            DateTime dtDateFrom = new DateTime(_dtDateFrom.Year, _dtDateFrom.Month, _dtDateFrom.Day);
            string strKeyword = "VietNamAirlineBootSearchCheapest" + _strStationForm + _strStationTo + dtDateFrom.ToString("MMyyyy") +
                    (_dtDateTo.HasValue ? _dtDateTo.Value.ToString("MMyyyy") : "") + _iAdut.ToString() + _iChild.ToString() + _iBaby.ToString() + "_User" + SettingDAO.UserID;
            //m_log.Info("Search: " + strKeyword);
            //var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            var cacheResult = CacheManager.GetInstance().Get(strKeyword);
            if (cacheResult != null)
            {
                //m_log.Info("Get from cache");
                return (List<TicketDTO>)cacheResult;
            }

            //lần 1
            dtDateFrom = new DateTime(dtDateFrom.Year, dtDateFrom.Month, 3);
            if (dtDateFrom < DateTime.Now)
                dtDateFrom = DateTime.Now.AddDays(3);
            if (_dtDateTo.HasValue)
            {
                _dtDateTo = new DateTime(_dtDateTo.Value.Year, _dtDateTo.Value.Month, 3);
                if (_dtDateTo.Value < DateTime.Now)
                    _dtDateTo = DateTime.Now.AddDays(3);
            }

            WorkerManager wkBus = new WorkerManager();

            wkBus.Add(new FindCheapestWorkerVN("VietNamAirlinePart1", new VietNamAirline(), ComineTickets, _strStationForm, _strStationTo, dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby));

            //lần 2
            dtDateFrom = dtDateFrom.AddDays(7);
            if (_dtDateTo.HasValue)
                _dtDateTo = _dtDateTo.Value.AddDays(7);
            if (dtDateFrom.AddDays(-4).Month == _dtDateFrom.Month)
                wkBus.Add(new FindCheapestWorkerVN("VietNamAirlinePart2", new VietNamAirline(), ComineTickets, _strStationForm, _strStationTo, dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby));

            //lần 3
            dtDateFrom = dtDateFrom.AddDays(7);
            if (_dtDateTo.HasValue)
                _dtDateTo = _dtDateTo.Value.AddDays(7);
            if (dtDateFrom.AddDays(-4).Month == _dtDateFrom.Month)
                wkBus.Add(new FindCheapestWorkerVN("VietNamAirlinePart3", new VietNamAirline(), ComineTickets, _strStationForm, _strStationTo, dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby));

            //lần 4
            dtDateFrom = dtDateFrom.AddDays(7);
            if (_dtDateTo.HasValue)
                _dtDateTo = _dtDateTo.Value.AddDays(7);
            if (dtDateFrom.AddDays(-4).Month == _dtDateFrom.Month)
                wkBus.Add(new FindCheapestWorkerVN("VietNamAirlinePart4", new VietNamAirline(), ComineTickets, _strStationForm, _strStationTo, dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby));

            //lần 5
            dtDateFrom = dtDateFrom.AddDays(7);
            if (_dtDateTo.HasValue)
                _dtDateTo = _dtDateTo.Value.AddDays(7);
            if (dtDateFrom.AddDays(-4).Month == _dtDateFrom.Month)
                wkBus.Add(new FindCheapestWorkerVN("VietNamAirlinePart5", new VietNamAirline(), ComineTickets, _strStationForm, _strStationTo, dtDateFrom, _dtDateTo, _iAdut, _iChild, _iBaby));

            wkBus.Run();


            if (m_lstResult != null)
            {
                //CacheManager.GetInstance().Add(strKeyword, lstResult.ToList());
                CacheManager.GetInstance().Add(strKeyword, m_lstResult.ToList());
            }
            return m_lstResult;
        }

        public List<TicketDTO> SearchCheapestPart1(string _strStationForm, string _strStationTo, DateTime _dtDateFrom, DateTime? _dtDateTo,
            int _iAdut, int _iChild, int _iBaby)
        {
            //https://wl-prod.sabresonicweb.com/SSW2010/B3QE/webqtrip.html?searchType=NORMAL&lang=vt&journeySpan=OW&origin=SGN&destination=DAD&numAdults=1&numChildren=0&numInfants=0&promoCode=&radio_choice=on&txtRecordLocator=&txtETicketNumber=&txtFFNumber=&alternativeLandingPage=true&departureDate=2014-03-4&
            string strResquest = string.Format("https://wl-prod.sabresonicweb.com/SSW2010/B3QE/webqtrip.html?searchType=NORMAL&lang=vt&journeySpan={0}&origin={1}&destination={2}&numAdults={3}&numChildren={4}&numInfants={5}&promoCode=&radio_choice=on&txtRecordLocator=&txtETicketNumber=&txtFFNumber=&alternativeLandingPage=true&departureDate={6}&{7}",
                _dtDateTo.HasValue ? "RT" : "OW",//0
                _strStationForm,//1
                _strStationTo,//2
                _iAdut,//3
                _iChild,//4
                _iBaby,//5
                _dtDateFrom.ToString("yyyy-MM-dd"),
                _dtDateTo.HasValue ? string.Format("returnDate={0}&", _dtDateTo.Value.ToString("yyyy-MM-dd")) : ""
                );
            List<TicketDTO> lstResult = new List<TicketDTO>();
            Requester re = new Requester();
            var res = re.GetData(strResquest);
            string htmlResult = re.GetHtmlFromResponse(res);
            if (string.IsNullOrEmpty(htmlResult))
            {
                LogManager.GetInstance().Warning("VN SearchCheapestPart1: Can't get data");
                return lstResult;
            }
            //yui-module yuimenubar
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(htmlResult);
            var travels = doc.DocumentNode.SelectNodes("//*[@class=\"yui-module yuimenubar\"]");
            if (travels == null)
            {
                LogManager.GetInstance().Warning("VN SearchCheapestPart1: Can't find flights");
                return lstResult;
            }
            if (_dtDateTo.HasValue && travels.Count != 2)
                throw new Exception("Không tìm dc lượt về");

            var iFee = Int32.Parse(new SettingDAO().GetSetting("FeeVietnamAirline"));
            for (int i = 0; i < travels.Count; i++)
            {
                HtmlDocument doctds = new HtmlDocument();
                doctds.LoadHtml(travels[i].InnerHtml);
                var tickets = doctds.DocumentNode.SelectNodes("//li");
                foreach (var ticket in tickets)
                {
                    HtmlDocument docTicket = new HtmlDocument();
                    docTicket.LoadHtml(ticket.InnerHtml);
                    TicketDTO t = new TicketDTO();
                    t.AirType = "vietnam";
                    string strDate = docTicket.DocumentNode.SelectNodes("//*[@class=\"date translate wasTranslated\"]")[0].Attributes["wl:date"].Value;
                    strDate = strDate.Split(' ')[0];
                    t.DateStart = DateTime.ParseExact(strDate, "yyyy/M/d", null);
                    t.DateEnd = t.DateStart;
                    //prices-amount
                    var nodePrice = docTicket.DocumentNode.SelectNodes("//*[@class=\"prices-amount\"]");
                    string strPrice = "0";
                    if (nodePrice != null)
                        strPrice = nodePrice[0].InnerText.Replace(",", "");
                    if (strPrice == "")
                    {
                        strPrice = "0";
                    }
                    t.PriceBefore = Int32.Parse(strPrice);
                    t.Price = t.PriceBefore + iFee;
                    t.FlightNo = "VN";
                    t.From = _strStationForm;
                    t.To = _strStationTo;
                    t.Image = "http://thegioivere.net/content/images/logo/VN.png";
                    lstResult.Add(t);
                    t.TypeWay = i == 0 ? "Out" : "In";
                }
            }
            return lstResult;
        }


        public int MakeBooking(BK_Booking booking, BK_Passenger[] passenges, TicketDTO tkDepart, TicketDTO tkReturn)
        {
            int iDayTimeOut = Int32.Parse(new SettingDAO().GetSetting("TimeoutBookVietnamAirline"));

            if (tkDepart.DateStart.AddHours(iDayTimeOut) <= DateTime.Now)
            {
                LogManager.GetInstance().Warning("VietNamAirline: Out of booking date");
                return (int)BookingStatus.OUTOFBOOKING;
            }

            if (tkReturn != null)
            {
                return BookingTowWay(booking, passenges, tkDepart, tkReturn);
            }
            else
            {
                return BookingOneWay(booking, passenges, tkDepart);
            }
        }

        public int BookingOneWay(BK_Booking booking, BK_Passenger[] passenges, TicketDTO tkDepart)
        {
            string strEmailDefault = "thegioivere@gmail.com";
            string html = "";
            string strRound = "ONEWAY";

            int _iAdut = passenges.Count(m => m.TypeID == 1);
            int _iChild = passenges.Count(m => m.TypeID == 2);
            int _iBaby = passenges.Count(m => m.TypeID == 3);

            #region 1.Đăng nhập
            if (!Login())
            {
                LogManager.GetInstance().Warning("VietNamAirline: Not login");
                return (int)BookingStatus.NOTLOGIN;
            }

            #endregion

            #region 2.Tìm vé

            var data = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("Action", "SEARCHFLIGHT"),
                new KeyValuePair<string, string>("OldSearchType", ""),
                new KeyValuePair<string, string>("SearchType", strRound),
                new KeyValuePair<string, string>("SearchRoundTripDepartureCity", booking.FromCity),
                new KeyValuePair<string, string>("SearchRoundTripArrivalCity", booking.ToCity),
                new KeyValuePair<string, string>("SearchRoundTripDepartureDate" ,tkDepart.DateStart.ToString("dd/MM/yyyy")),
                //new KeyValuePair<string, string>("SearchRoundTripArrivalDate",tkReturn!=null? tkReturn.DateStart.ToString("dd/MM/yyyy"):""),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", booking.FromCity),
                new KeyValuePair<string, string>("SearchOneWayArrivalCity", booking.ToCity),
                new KeyValuePair<string, string>("SearchOneWayDepartureDate", tkDepart.DateStart.ToString("dd/MM/yyyy")),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", "SGN"),
            });
            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");

            var request = (HttpWebRequest)WebRequest.Create(m_strHomeLink + "Booking/BookManage");
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.CookieContainer = co;
            using (var requestStream = request.GetRequestStream())
            using (var writer = new StreamWriter(requestStream))
            {
                foreach (var item in data)
                {
                    writer.WriteLine("--" + boundary);
                    writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", item.Key));
                    writer.WriteLine();
                    writer.WriteLine(item.Value);
                }
                writer.WriteLine(boundary + "--");
            }

            string strOutTicket = "";
            using (var response = request.GetResponse())
            using (var responseStream = response.GetResponseStream())
            using (var reader = new StreamReader(responseStream))
            {
                html = reader.ReadToEnd();
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);


                var OutTickets = doc.DocumentNode.SelectNodes(string.Format("//a[contains(@onclick,'FillToBooking') and contains(@onclick,'AGT') and contains(@onclick,'{0};{1};{2};{3}')]",//SGN;HAN;VN234;06/01/2014;0930
                    booking.FromCity.ToUpper(),//0
                    booking.ToCity.ToUpper(),//1
                    tkDepart.FlightNo.ToUpper().Replace(" ", ""),//2
                    tkDepart.DateStart.ToString("dd/MM/yyyy;HHmm")//3
                        )
                    );//
                if (OutTickets.Count > 0)
                {

                    for (int i = OutTickets.Count - 1; i >= 0; i--)
                    {
                        string strclass = OutTickets[i].InnerText.Trim();
                        if (strclass[0] == 'X')
                            continue;
                        strclass = strclass.Substring(1);
                        if (!string.IsNullOrEmpty(strclass)
                            && strclass != "0"
                            && Int32.Parse(strclass) >= _iAdut + _iBaby + _iChild
                            )
                        {
                            strOutTicket = OutTickets[i].Attributes["onclick"].Value;
                            break;
                        }
                    }
                }
            }

            #endregion

            #region 3.Chọn vé

            if (strOutTicket == "")
                throw new Exception("Không tìm thấy vé đi");

            strOutTicket = strOutTicket.Substring(strOutTicket.IndexOf('\'') + 1, strOutTicket.LastIndexOf('\'') - strOutTicket.IndexOf('\'') - 1);
            // SGN;HAN;VN244;10/01/2014;1300;J;4,600,000;NN;3;VN130471F_J;AGT;5,120,000
            //'SGN;HAN;VN234;06/01/2014;0930;M;2,670,000;LL;1;VN130471F_M;AGT;2,997,000
            //  0   1     2      3        4  5     6     7  8      9      10     11
            var arrOut = strOutTicket.Split(';');
            #endregion

            data = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("Action", "BOOK"),
                new KeyValuePair<string, string>("BookType", "ONEWAY"),
                new KeyValuePair<string, string>("BookOneWayDepartureCity", booking.FromCity),
                new KeyValuePair<string, string>("BookOneWayArrivalCity", booking.ToCity),
                new KeyValuePair<string, string>("BookOneWayDepartureFlightCode", arrOut[2]),
                new KeyValuePair<string, string>("BookOneWayDepartureDate", arrOut[3]),
                new KeyValuePair<string, string>("BookOneWayDepartureTime", arrOut[4]),
                new KeyValuePair<string, string>("BookOneWayDepartureSeatClass", arrOut[5]),
                new KeyValuePair<string, string>("BookOneWayDeparturePrice", arrOut[6]),
                new KeyValuePair<string, string>("BookOneWayDepartureActionCode", arrOut[7])
});
            int iTotalTickets = passenges.Count(m => m.TypeID == 1 || m.TypeID == 2);

            var data1 = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("BookNumofPassenger", iTotalTickets.ToString())
                //new KeyValuePair<string, string>("BookPassenger1FullName", "Tran Tuan Vu"),
                //new KeyValuePair<string, string>("BookPassenger1Title", "ADULT")
            });
            for (int i = 0; i < iTotalTickets; i++)
            {
                string strTitle = "";
                if (passenges[i].Sex == "M")
                {
                    if (passenges[i].TypeID == 1)
                        strTitle = "MR";
                    else
                        strTitle = "MSTR";
                }
                else
                {
                    if (passenges[i].TypeID == 1)
                        strTitle = "MS";
                    else
                        strTitle = "MISS";
                }
                data1.Add(new KeyValuePair<string, string>("BookPassenger" + (i + 1).ToString() + "FullName", passenges[i].FirstName + " " + passenges[i].Name));
                data1.Add(new KeyValuePair<string, string>("BookPassenger" + (i + 1).ToString() + "Title", strTitle));
            }
            var data2 = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("IsTicketingPrice", "true"),
                new KeyValuePair<string, string>("IsTicketingPrice", "false"),
                new KeyValuePair<string, string>("TicketingPrice", "0"),
                new KeyValuePair<string, string>("CalculateTotal", "3,250,000"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureAdult", "1"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureAdultPrice", "2,900,000"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureAdultVAT", "350,000"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureAdultPriceVAT", "3,250,000"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureAdultTotalPrice", "3,250,000"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureChild", "0"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureChildPrice", "2,175,000"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureChildVAT", "247,500"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureChildTotalPrice", "0"),
                new KeyValuePair<string, string>("CalculateOneWayDepartureTotalPrice", "3,250,000"),
                new KeyValuePair<string, string>("BookPhone", passenges[0].Phone),
                new KeyValuePair<string, string>("BookPhoneReMark", ""),
                new KeyValuePair<string, string>("BookEmail", strEmailDefault),
                new KeyValuePair<string, string>("SendBy", "BOTH"),
                new KeyValuePair<string, string>("BookReMark", ""),
                new KeyValuePair<string, string>("BookTicketFace", ""),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", "SGN")
            });
            data.AddRange(data1);
            data.AddRange(data2);
            boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");

            request = (HttpWebRequest)WebRequest.Create(m_strHomeLink + "Booking/BookManage");
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.CookieContainer = co;
            using (var requestStream = request.GetRequestStream())
            using (var writer = new StreamWriter(requestStream))
            {
                foreach (var item in data)
                {
                    writer.WriteLine("--" + boundary);
                    writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", item.Key));
                    writer.WriteLine();
                    writer.WriteLine(item.Value);
                }
                writer.WriteLine(boundary + "--");
            }

            using (var response = request.GetResponse())
            using (var responseStream = response.GetResponseStream())

            using (var reader = new StreamReader(responseStream))
            {
                html = reader.ReadToEnd();
                //if (html.IndexOf("Thao tác thành công") != -1 && html.IndexOf("Thao t&#225;c th&#224;nh c&#244;ng") != -1)
                {
                    GetThongTinSauKhiDatVe(html);
                }
            }
            if (resnumber != "" && thanhtien != "")
            {
                AddChild(passenges);
                return 1;
            }
            return 0;
        }
        public int BookingTowWay(BK_Booking booking, BK_Passenger[] passenges, TicketDTO tkDepart, TicketDTO tkReturn)
        {
            string strEmailDefault = "thegioivere@gmail.com";
            string html = "";
            string strRound = "ONEWAY";
            if (tkReturn != null)
                strRound = "ROUNDTRIP";

            int _iAdut = passenges.Count(m => m.TypeID == 1);
            int _iChild = passenges.Count(m => m.TypeID == 2);
            int _iBaby = passenges.Count(m => m.TypeID == 3);

            #region 1.Đăng nhập
            if (!Login())
            {
                LogManager.GetInstance().Warning("VietNamAirline: Not login");
                return (int)BookingStatus.NOTLOGIN;
            }

            #endregion

            #region 2.Tìm vé

            var data = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("Action", "SEARCHFLIGHT"),
                new KeyValuePair<string, string>("OldSearchType", ""),
                new KeyValuePair<string, string>("SearchType", strRound),
                new KeyValuePair<string, string>("SearchRoundTripDepartureCity", booking.FromCity),
                new KeyValuePair<string, string>("SearchRoundTripArrivalCity", booking.ToCity),
                new KeyValuePair<string, string>("SearchRoundTripDepartureDate" ,tkDepart.DateStart.ToString("dd/MM/yyyy")),
                new KeyValuePair<string, string>("SearchRoundTripArrivalDate",tkReturn!=null? tkReturn.DateStart.ToString("dd/MM/yyyy"):""),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", booking.FromCity),
                new KeyValuePair<string, string>("SearchOneWayArrivalCity", booking.ToCity),
                new KeyValuePair<string, string>("SearchOneWayDepartureDate", tkDepart.DateStart.ToString("dd/MM/yyyy")),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", "SGN"),
            });
            string boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");

            var request = (HttpWebRequest)WebRequest.Create(m_strHomeLink + "Booking/BookManage");
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.CookieContainer = co;
            using (var requestStream = request.GetRequestStream())
            using (var writer = new StreamWriter(requestStream))
            {
                foreach (var item in data)
                {
                    writer.WriteLine("--" + boundary);
                    writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", item.Key));
                    writer.WriteLine();
                    writer.WriteLine(item.Value);
                }
                writer.WriteLine(boundary + "--");
            }

            string strOutTicket = "";
            string strInTicket = "";
            using (var response = request.GetResponse())
            using (var responseStream = response.GetResponseStream())
            using (var reader = new StreamReader(responseStream))
            {
                html = reader.ReadToEnd();
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);


                var OutTickets = doc.DocumentNode.SelectNodes(string.Format("//a[contains(@onclick,'FillToBooking') and contains(@onclick,'AGT') and contains(@onclick,'{0};{1};{2};{3}')]",//SGN;HAN;VN234;06/01/2014;0930
                    booking.FromCity.ToUpper(),//0
                    booking.ToCity.ToUpper(),//1
                    tkDepart.FlightNo.ToUpper().Replace(" ", ""),//2
                    tkDepart.DateStart.ToString("dd/MM/yyyy;HHmm")//3
                        )
                    );//


                if (OutTickets.Count > 0)
                {
                    for (int i = OutTickets.Count - 1; i >= 0; i--)
                    {
                        string strclass = OutTickets[i].InnerText.Trim();
                        if (strclass[0] == 'X')
                            continue;
                        strclass = strclass.Substring(1);
                        if (!string.IsNullOrEmpty(strclass)
                            && strclass != "0"
                            && Int32.Parse(strclass) >= _iAdut + _iBaby + _iChild
                            )
                        {
                            strOutTicket = OutTickets[i].Attributes["onclick"].Value;
                            break;
                        }
                    }
                }
                else
                {
                    LogManager.GetInstance().Warning("VietNamAirline: Search 0 result tickets");
                    return (int)BookingStatus.NORESULTFIND;
                }
                if (tkReturn != null)
                {
                    var InTickets = doc.DocumentNode.SelectNodes(string.Format("//a[contains(@onclick,'FillToBooking') and contains(@onclick,'AGT') and contains(@onclick,'{0};{1};{2};{3}')]",//SGN;HAN;VN234;06/01/2014;0930
                    booking.ToCity.ToUpper(),//1
                    booking.FromCity.ToUpper(),//0
                    tkReturn.FlightNo.ToUpper().Replace(" ", ""),//2
                    tkReturn.DateStart.ToString("dd/MM/yyyy;HHmm")//3
                        )
                    );//
                    if (InTickets.Count > 0)
                    {
                        for (int i = InTickets.Count - 1; i > 0; i--)
                        {
                            string strclass = InTickets[i].InnerText.Trim();
                            if (strclass[0] == 'X')
                                continue;
                            strclass = strclass.Substring(1);
                            if (strclass != "0")
                            {
                                strInTicket = InTickets[i].Attributes["onclick"].Value;
                                break;
                            }
                        }
                    }
                    else
                    {
                        LogManager.GetInstance().Warning("VietNamAirline: No ticket avaliable");
                        return (int)BookingStatus.NORESULTFIND;
                    }
                }
            }

            #endregion

            #region 3.Chọn vé

            if (strOutTicket == "")
            {
                LogManager.GetInstance().Warning("VietNamAirline: No depart ticket avaliable");
                return (int)BookingStatus.NOTMACTHDEPART;
            }
            if (tkReturn != null)
            {
                if (strInTicket == "")
                {
                    LogManager.GetInstance().Warning("VietNamAirline: No return ticket avaliable");
                    return (int)BookingStatus.NOTMACTHRETURN;
                }
                else
                {
                    strInTicket = strInTicket.Substring(strInTicket.IndexOf('\''), strInTicket.LastIndexOf('\'') - strInTicket.IndexOf('\''));
                }
            }
            strOutTicket = strOutTicket.Substring(strOutTicket.IndexOf('\''), strOutTicket.LastIndexOf('\'') - strOutTicket.IndexOf('\''));

            //'SGN;HAN;VN234;06/01/2014;0930;M;2,670,000;LL;1;VN130471F_M;AGT;2,997,000
            //  0   1     2      3        4  5 6  7       8 9      10      11     12
            var arrOut = strOutTicket.Split(';');
            var arrIn = strInTicket.Split(';');
            #endregion

            #region Điền thông tin

            data = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("Action", "BOOK"),
                new KeyValuePair<string, string>("SearchRoundTripDepartureCity", booking.FromCity),
                new KeyValuePair<string, string>("SearchRoundTripArrivalCity", booking.ToCity),
                new KeyValuePair<string, string>("SearchRoundTripDepartureDate", tkDepart.DateStart.ToString("dd/MM/yyyy")),
                new KeyValuePair<string, string>("SearchRoundTripArrivalDate", tkReturn!=null ? tkReturn.DateStart.ToString("dd/MM/yyyy"):""),
                new KeyValuePair<string, string>("BookType", strRound),
                new KeyValuePair<string, string>("BookRoundTripDepartureCity", booking.FromCity),
                new KeyValuePair<string, string>("BookRoundTripArrivalCity", booking.ToCity),
                new KeyValuePair<string, string>("BookRoundTripDepartureFlightCode", arrOut[2]),
                new KeyValuePair<string, string>("BookRoundTripDepartureDate",arrOut[3]),
                new KeyValuePair<string, string>("BookRoundTripDepartureTime", arrOut[4]),
                new KeyValuePair<string, string>("BookRoundTripDepartureSeatClass", arrOut[5]),
                new KeyValuePair<string, string>("BookRoundTripDeparturePrice", arrOut[6]),
                new KeyValuePair<string, string>("BookRoundTripDepartureActionCode", arrOut[7]),
                new KeyValuePair<string, string>("BookRoundTripArrivalFlightCode",strInTicket!=""? arrIn[2]:""),
                new KeyValuePair<string, string>("BookRoundTripArrivalDate",strInTicket!=""? arrIn[3]:""),
                new KeyValuePair<string, string>("BookRoundTripArrivalTime", strInTicket!=""?arrIn[4]:""),
                new KeyValuePair<string, string>("BookRoundTripArrivalSeatClass", strInTicket!=""?arrIn[5]:""),
                new KeyValuePair<string, string>("BookRoundTripArrivalPrice", strInTicket!=""?arrIn[6]:""),
                new KeyValuePair<string, string>("BookRoundTripArrivalActionCode", strInTicket!=""?arrIn[7]:""),

                new KeyValuePair<string, string>("BookOneWayDepartureCity", booking.FromCity),
                new KeyValuePair<string, string>("BookOneWayArrivalCity", booking.ToCity),
                new KeyValuePair<string, string>("BookOneWayDepartureFlightCode", arrOut[2]),
                new KeyValuePair<string, string>("BookOneWayDepartureDate",arrOut[3]),
                new KeyValuePair<string, string>("BookOneWayDepartureTime", arrOut[4]),
                new KeyValuePair<string, string>("BookOneWayDepartureSeatClass", arrOut[5]),
                new KeyValuePair<string, string>("BookOneWayDeparturePrice", arrOut[6]),
                new KeyValuePair<string, string>("BookOneWayDepartureActionCode", arrOut[7]),
                
          
});
            int iTotalTickets = passenges.Count(m => m.TypeID == 1 || m.TypeID == 2);

            var data1 = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("BookNumofPassenger", iTotalTickets.ToString())
                //new KeyValuePair<string, string>("BookPassenger1FullName", "Tran Tuan Vu"),
                //new KeyValuePair<string, string>("BookPassenger1Title", "ADULT")
            });
            for (int i = 0; i < iTotalTickets; i++)
            {
                string strTitle = "";
                if (passenges[i].Sex == "M")
                {
                    if (passenges[i].TypeID == 1)
                        strTitle = "MR";
                    else
                        strTitle = "MSTR";
                }
                else
                {
                    if (passenges[i].TypeID == 1)
                        strTitle = "MS";
                    else
                        strTitle = "MISS";
                }
                data1.Add(new KeyValuePair<string, string>("BookPassenger" + (i + 1).ToString() + "FullName", passenges[i].FirstName + " " + passenges[i].Name));
                data1.Add(new KeyValuePair<string, string>("BookPassenger" + (i + 1).ToString() + "Title", strTitle));

            }

            var data2 = new List<KeyValuePair<string, string>>(new[]
            {
                new KeyValuePair<string, string>("IsTicketingPrice", "true"),
                new KeyValuePair<string, string>("IsTicketingPrice", "false"),
                new KeyValuePair<string, string>("TicketingPrice", "0"),
                new KeyValuePair<string, string>("CalculateTotal", "10,240,000"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureAdult", "0"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureAdultPrice", "4,600,000"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureAdultVAT", "520,000"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureAdultPriceVAT", "5,120,000"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureAdultTotalPrice", "5,120,000"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureChild", "0"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureChildPrice", "4,600,000"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureChildVAT", "520,000"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureChildTotalPrice", "0"),
                new KeyValuePair<string, string>("CalculateRoundTripDepartureTotalPrice", "5,120,000"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalAdult", "1"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalAdultPrice", "4,600,000"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalAdultVAT", "520,000"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalAdultPriceVAT", "5,120,000"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalAdultTotalPrice", "5,120,000"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalChild", "0"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalChildPrice", "4,600,000"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalChildVAT", "520,000"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalChildTotalPrice", "0"),
                new KeyValuePair<string, string>("CalculateRoundTripArrivalTotalPrice", "5,120,000"),
                new KeyValuePair<string, string>("BookPhone", passenges[0].Phone),
                new KeyValuePair<string, string>("BookPhoneReMark", ""),
                new KeyValuePair<string, string>("BookEmail", strEmailDefault),
                new KeyValuePair<string, string>("SendBy", "BOTH"),
                new KeyValuePair<string, string>("BookReMark", ""),
                new KeyValuePair<string, string>("BookTicketFace", ""),
                new KeyValuePair<string, string>("SearchOneWayDepartureCity", "SGN")
            });

            data.AddRange(data1);
            data.AddRange(data2);

            boundary = "----WebKitFormBoundary" + DateTime.Now.Ticks.ToString("x");

            request = (HttpWebRequest)WebRequest.Create(m_strHomeLink + "Booking/BookManage");
            request.ContentType = "multipart/form-data; boundary=" + boundary;
            request.Method = "POST";
            request.CookieContainer = co;
            using (var requestStream = request.GetRequestStream())
            using (var writer = new StreamWriter(requestStream))
            {
                foreach (var item in data)
                {
                    writer.WriteLine("--" + boundary);
                    writer.WriteLine(string.Format("Content-Disposition: form-data; name=\"{0}\"", item.Key));
                    writer.WriteLine();
                    writer.WriteLine(item.Value);
                }
                writer.WriteLine(boundary + "--");
            }

            using (var response = request.GetResponse())
            using (var responseStream = response.GetResponseStream())

            using (var reader = new StreamReader(responseStream))
            {
                html = reader.ReadToEnd();
                //if (html.IndexOf("Thao tác thành công") != -1 && html.IndexOf("Thao t&#225;c th&#224;nh c&#244;ng") != -1)
                {
                    try
                    {
                        GetThongTinSauKhiDatVe(html);
                        AddChild(passenges);
                        return 1;
                    }
                    catch { }
                }
            }

            #endregion

            return 0;//Đặt vé không thành công
        }

        private void AddChild(BK_Passenger[] passenges)
        {
            #region Thêm em bé
            if (resnumber.Trim() != "")
            {
                var lstBabies = passenges.Where(m => m.TypeID == 3).ToArray();
                if (lstBabies != null && lstBabies.Length != 0)
                {

                    #region Get page search GET http://www.bookingticket.vn/Book/BookManual

                    var resAddInfant = m_request.GetData(m_strHomeLink + "Book/BookManual", false, co);
                    string htmlAddInfant = m_request.GetHtmlFromResponse(resAddInfant);

                    HtmlDocument docAddInfant = new HtmlDocument();
                    docAddInfant.LoadHtml(htmlAddInfant);

                    #endregion


                    #region Post search POST http://www.bookingticket.vn/Book/BookManual

                    //Get data to search
                    var lst = HtmlHelper.GetFormData(htmlAddInfant, "//*[@id=\"hContentBox\"]");

                    lst = HtmlHelper.UpdateFormData(lst, "RecordLocation", resnumber.Trim());
                    lst = HtmlHelper.UpdateFormData(lst, "Action", "SEARCHBOOK");

                    string strData = HtmlHelper.GenFormData(lst);

                    resAddInfant = m_request.PostData(m_strHomeLink + "Book/BookManual", strData, false, co);
                    htmlAddInfant = m_request.GetHtmlFromResponse(resAddInfant);



                    #endregion

                    #region Post add infant POST http://www.bookingticket.vn/Book/BookManual

                    for (int i = 0; i < lstBabies.Length; i++)
                    {

                        //Get data to search
                        lst = HtmlHelper.GetFormData(htmlAddInfant, "//*[@id=\"hContentBox\"]");

                        lst = HtmlHelper.UpdateFormData(lst, "AddInfantFollowPassenger", string.Format("{0}.1", i + 1));
                        lst = HtmlHelper.UpdateFormData(lst, "AddInfantFullName", lstBabies[i].FirstName + " " + lstBabies[i].Name);
                        lst = HtmlHelper.UpdateFormData(lst, "AddInfantTitle", lstBabies[i].Sex == "M" ? "MSTR" : "MISS");
                        lst = HtmlHelper.UpdateFormData(lst, "AddInfantBirthDay", lstBabies[i].Birthday.Value.ToString("dd/MM/yyyy"));
                        lst = HtmlHelper.UpdateFormData(lst, "Action", "ADDINFANT");

                        strData = HtmlHelper.GenFormData(lst);

                        resAddInfant = m_request.PostData(m_strHomeLink + "Book/BookManual", strData, false, co);
                        htmlAddInfant = m_request.GetHtmlFromResponse(resAddInfant);
                    }



                    #endregion
                }
            }
            #endregion
        }


        public string resnumber = "";
        public string thanhtien = "";
        private string m_error;
        private string phixuatve;
        public void GetThongTinSauKhiDatVe(string html)
        {
            HtmlDocument docDepart = new HtmlDocument();
            docDepart.LoadHtml(html);
            var nodesresnumber = docDepart.DocumentNode.SelectNodes("//*[@id=\"BookTicketFace\"]");
            resnumber = nodesresnumber[0].InnerText;
            string[] m = resnumber.Split('\n');

            resnumber = m[0];

            //var nodestotalmoney = docDepart.DocumentNode.SelectNodes("//*[@class=\"ChargesTotal\"]//td[2]");

            thanhtien = docDepart.DocumentNode.SelectNodes("//*[@id=\"FareTotalLabel\"]")[0].InnerText.Replace("\n", "").Replace(",", "");
            thanhtien = thanhtien.Replace("VND", "");

            phixuatve = docDepart.DocumentNode.SelectNodes("//*[@id=\"FareTicketingView\"]")[0].InnerText.Replace("\n", "").Replace(",", ""); 
            //
        }


        public bool Login()
        {
            string login = m_strHomeLink;
            //var reps = m_request.GetData(login);
            //string html = m_request.GetHtmlFromResponse(reps);


            var res = m_request.GetData(login, false, co);
            string html = m_request.GetHtmlFromResponse(res);
            if (html.IndexOf("Login/Logout") > -1)
            {
                //#region Dat cho
                //res = m_request.GetData("http://www.bookingticket.vn/Booking/BookManage", false, co);
                //html = m_request.GetHtmlFromResponse(res);

                //#endregion
                return true;
            }
            return false;
        }
        //public int MakeBooking(BK_Booking booking, BK_Passenger[] passenges, TicketDTO tkDepart, TicketDTO tkReturn)
        //{
        //    string strLink = "http://www.bookingticket.vn/Booking/BookManage";
        //    var res = m_request.GetData(strLink, false, co);
        //    string html = m_request.GetHtmlFromResponse(res);
        //    if (html.IndexOf("HGVTHANHLINH1") == -1)
        //        return -1;//chưa đăng nhập

        //    strLink = "http://www.bookingticket.vn/Booking/BookManage";
        //    string strData = "";
        //    return 0;
        //}

        //public List<TicketDTO> GetFromHtml(BK_Booking booking, BK_Passenger[] passenges, TicketDTO tkDepart, TicketDTO tkReturn)
        //{
        //    string html = System.IO.File.ReadAllText(@"vndata.txt");
        //    HtmlDocument doc = new HtmlDocument();
        //    doc.LoadHtml(html);


        //    var OutTickets = doc.DocumentNode.SelectNodes(string.Format("//a[contains(@onclick,'FillToBooking') and contains(@onclick,'AGT') and contains(@onclick,'{0};{1};{2};{3}')]",//SGN;HAN;VN234;06/01/2014;0930
        //        booking.FromCity.ToUpper(),//0
        //        booking.ToCity.ToUpper(),//1
        //        tkDepart.FlightNo.ToUpper(),//2
        //        tkDepart.DateStart.ToString("dd/MM/yyyy;HHmm")//3
        //            )
        //        );//

        //    var InTickets = doc.DocumentNode.SelectNodes(string.Format("//a[contains(@onclick,'FillToBooking') and contains(@onclick,'AGT') and contains(@onclick,'{0};{1};{2};{3}')]",//SGN;HAN;VN234;06/01/2014;0930
        //        booking.ToCity.ToUpper(),//1
        //        booking.FromCity.ToUpper(),//0
        //        tkReturn.FlightNo.ToUpper(),//2
        //        tkReturn.DateStart.ToString("dd/MM/yyyy;HHmm")//3
        //            )
        //        );//

        //    return null;
        //}


        public decimal GetOutputFee(decimal TotalPrice, DateTime StartDate)
        {
            return 0;
        }
    }
}
